<template>
    <div>
            <!-- 发表说说 -->
        <q-fixed-position corner="bottom-right" :offset="[0, 20]">
          <q-btn
            color="blue-grey-8"
            round
            :icon="isAddIcon? 'add':'reply'"
            class="animate-pop"
            @click="publishSomething"
          />
      </q-fixed-position>  

      <q-modal ref="inputModal"  :content-css="{minWidth: '50vw', minHeight: '50vh'}">
      <q-modal-layout >
         <q-toolbar slot="header" >
           <q-btn color="warning" big  flat @click="closeInputModal">取消 </q-btn>
           <q-toolbar-title style="text-align:center">
             <q-icon name="create"/> 说两句
          </q-toolbar-title>
        </q-toolbar>

        <div class="layout-padding">
            <q-field
                :count="250"
              >
               <q-input 
                  v-model="commitResult.content"  
                  max-length="250" 
                  type="textarea"
                  style="width: 100%;height:100%" 
                  placeholder="回复一个兴趣话题/记录一段瞬时灵感"
                  />
            </q-field>
            <div class="view-colors">
              <div
                  class="main-color shadow-10 row inline"
                  v-for="(upimage,index) in imagesPriview"
                  :key="index"
                >
                <q-icon color="red" name="remove circle" />
                <img class="responsive" :src="upimage" style="width:100px;height:80px" @click="removeOne(index)">
             </div>
             </div>
        </div>

        <q-toolbar slot="footer" inverted>
            <q-btn v-if="enablePicChoice" flat rounded color="dark"  @click="$refs.selectImage.click()" icon="photo library"></q-btn>
            <!-- capture="camera"  -->
            <input id="upload" ref="selectImage" type="file" accept="image/*" @change="selectImageAction($refs.selectImage.files)"
                    multiple style="display: none;width:0;height:0"/>

            <q-toolbar-title style="text-align:right">
                <q-btn outline  color="dark"  @click="commitAction" icon-right="send" loader>发布</q-btn>
            </q-toolbar-title>
        </q-toolbar>
      </q-modal-layout>
    </q-modal>
    </div>
</template>

<script>
import {
  Alert,
  Ripple,
  QBtn,
  QIcon,
  QModal,
  QModalLayout,
  QToolbar,
  QToolbarTitle,
  QInput,
  QField,
  Dialog,
  QFixedPosition
} from "quasar";
import commonApiHttp from "../../https/commonApi";
import customerApi from '../../https/customerApi';
import Storage from '../../utils/storage'
import PicUtils from '../../utils/PicUtils'
//数组的角标删除
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

export default {
  components: {
    QBtn,
    QIcon,
    QModal,
    QModalLayout,
    QToolbar,
    QToolbarTitle,
    QInput,
    QField,
    Alert,
    Dialog,
    QFixedPosition
  },
  directives: {
    Ripple
  },
  data() {
    return {
      imagesPriview: [], //预览图片
      imagesSrc: [], //原始图片
      commitResult: { content: "" } //发布提交结果
    };
  },
  props: {
    enablePicChoice: { type: Boolean, default: true },
    isAddIcon: { type: Boolean, default: true }
  },
  mounted() {
    // this.$refs.inputModal.open();
  },
  methods: {
    clearDatas(){
      this.imagesPriview=[], //预览图片
      this.imagesSrc=[], //原始图片
      this.commitResult={ content: "" } //发布提交结果
    },
    publishSomething(){
      customerApi
          .userinfo()
          .then(res => {
            const { status, data } = res;
            if (status == 200 && data) {
              Storage.saveuser(data);
              this.$refs.inputModal.open()
            }else {
              this.$router.replace("/login")
            }
          })
          .catch(err => {});
    },
    closeInputModal(){
       this.$refs.inputModal.close();
       console.log('清除文件');
       this.clearDatas();
       document.getElementById('upload').value='';
    },
    showSelectLoading(_delay) {
      if(!_delay) {_delay = 2000}
      const _temp = Dialog.create({
        message: "正在处理中，请稍后...",
        progress: {
          indeterminate: true
        },
        buttons: [
          {
            label: "知道了",
            handler(data) {
              clearTimeout(timeout);
            }
          }
        ]
      });
      const timeout = setTimeout(() => {
        clearTimeout(timeout);
        _temp.close();
      }, _delay);
    },
    removeOne(index) {
      this.imagesPriview.remove(index);
      this.imagesSrc.remove(index);
      console.log("待提交的文件：", this.imagesSrc);
    },
    commitAction(event, done) {//提交表单
      const _files = this.imagesSrc;
      const _counts = _files.length;
      if (_counts && _counts > 0) {
        let formdata = new FormData();
        for (let i = 0; i < _counts; i++) {
          formdata.append("files",  _files[i],"file"+i+"_"+Date.parse(new Date())+".jpg"); // 文件对象:"file_"+Date.parse(new Date())+".jpg"
        }
        commonApiHttp
          .uploadFilesCompress(formdata, 720, 480)
          .then(res => {
            const { status, data } = res;
            if (status == 200 && data) {
              this.commitResult.attashments = data;
              console.log("文件上传成功：", this.commitResult);
              this.$emit("commit-result", this.commitResult);
              this.$refs.inputModal.close();
              done();
            }
          })
          .catch(err => {
            done();
            console.log("失败", err);
          });
      } else {
        if (this.commitResult.content) {
          this.$emit("commit-result", this.commitResult);
        }
        this.$refs.inputModal.close();
        done();
      }
    },
    alertMsg(msg) {
      if (msg) {
        const _errAlert = Alert.create({
          color: 'warning',
          icon: 'info',
          html: msg,
          position: 'bottom',
        });
        setTimeout(()=>{
          _errAlert.dismiss();
        },3000);
      }
    },
    checkFile(file, isDistinct) {//校验文件
      //类型
      if (
        !file ||
        !file.name ||
        !/.*(.jpg|.png|.gif|.jpeg|bmp)$/.test(file.name)
      ) {
        this.alertMsg("抱歉，不支持的文件类型");
        return false;
      }
      const _size = !isDistinct ? 5242880 : 1048576;
      //大小
      if (file.size > _size) {
        //5M
        this.alertMsg("抱歉，文件大小超出了5M的限制");
        return false;
      }
      return true;
    },
    selectImageAction(res) {//文件选择处理
      const newCount = res.length;
      if (this.imagesPriview.length + newCount > 6) {
        this.toastMsg("抱歉，最多只能上传6个文件");
        return false;
      }
      const reader = new FileReader();
      if (typeof FileReader === "undefined") {
        this.alertMsg("抱歉，您的设备不支持图片处理");
        //不支持类型的处理
        return false;
      }
      //校验类型，大小
      for (let i = 0; i < newCount; i++) {
        if (!this.checkFile(res[i], false)) {
          return false;
        }
      }
      this.showSelectLoading(newCount*1000);
      //多选
      let numbers = res.length - 1;
      const _wait = setInterval(() => {
        if (numbers < 0) {
          clearInterval(_wait);
        } else {
          const fileObj = res[numbers];
          PicUtils.photoCompress(//压缩
            fileObj,
            {
              quality: 0.6    //图片压缩质量,原图百分比
            },
            base64Codes => {
              this.imagesPriview.push(base64Codes);
              const bl = PicUtils.convertBase64UrlToBlob(base64Codes);
              console.log('压缩前：',fileObj.size,'压缩后：', bl.size);
              this.imagesSrc.push(bl);
              numbers--;
            }
          );
        }
      }, 1000);
      console.log("预览的文件：", this.imagesPriview);
      console.log("待提交的文件：", this.imagesSrc);
    }
  }
};
</script>

<style lang="styl" scoped>
.view-colors
  div.main-color
    width 100px
    margin 5px
    height 90px
</style>
